package com.lagou.Title3;

import org.w3c.dom.ls.LSOutput;

import java.io.*;
import java.util.concurrent.Callable;

public class Copy implements Callable {
    private File f1; //被复制的文件
    private File f2; //目标目录

    public Copy() {
    }

    public Copy(File f1, File f2) {
        this.f1 = f1;
        this.f2 = f2;
    }
    //复制文件到目标文件
    private void Copy(File f3, File f2)  {
        File f4 = new File(f2.getPath() +"/" +  f1.getName());

        //判断f3是文件还是目录
        String path = f4.getPath();
        if (f3.isDirectory()){
            //如果是目录则直接在对应的路径创建目录
            if(f4.exists()){
                System.out.println("目录" + path + "已经存在！");
            }else{
                System.out.println(f4.mkdir()? "目录" + path + "创建成功！":"目录" + f4.getPath() + "创建失败！");
            }
        }else if (f3.isFile()){
            //若是文件，就使用缓存字节输入输出流来复制文件到对应的路径
            BufferedInputStream bis = null;
            BufferedOutputStream bos = null;
            try {
                bis = new BufferedInputStream(new FileInputStream(f3));
                bos = new BufferedOutputStream(new FileOutputStream(f4));

                //开始读写
                byte[] arr = new byte[1025];
                int res = 0;
                while ((res = bis.read(arr)) != -1){
                    bos.write(arr,0,res);
                }
                System.out.println("复制文件" + f3.getName() + "成功！");
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                //关闭流并释放有关的资源
                if (null != bos) {
                    try {
                        bos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(null != bis) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        System.out.println("---------------------------");
    }
    //f3为被复制的文件
    //f2是目标目录
    private void copyFileRecursively(File f3, File f2){
        if (f3.exists()){
            //复制文件过去
            copyFileRecursively(f3,f2);

            //判断文件书否为目录，如果是目录则对其所有文件进行递归处理
            if (f3.isDirectory()){
                File[] files = f3.listFiles();
                //如果目录为空，则不进行递归
                if (files != null){
                    for (File tf : files){
                        copyFileRecursively(tf,new File(f2.getPath() + "/" + f3.getName()));
                    }
                }
            }
        }else{
            System.out.println("要被复制的文件不存在！");
        }
    }
    //重写call方法
    @Override
    public Object call() throws Exception {
        System.out.println("线程" + Thread.currentThread().getId() + "已经启动，源文件为"
                + this.f1 + "目标目录为：" + this.f2 + "。");
        copyFileRecursively(this.f1,this.f2);
        return null;
    }
}
